package ext.tianma.change.util;

import wt.enterprise.RevisionControlled;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.part.WTPartStandardConfigSpec;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.VersionControlHelper;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;

public class ChangeGetModifiedFinishedGood {
	
	
	/**
	 * 根据零部件编号，视图和版本获取零部件对象
	 * 
	 * @param number
	 * @param view
	 * @param version
	 * @return
	 * @throws WTException
	 */
	public static WTPart getWTPartByNumViewAndVersion(String number , String view , String version) throws WTException {
		WTPart part = null ;
		QuerySpec qs = new QuerySpec(WTPartMaster.class);
		
		//定义搜索条件，以零部件编号方式在master中搜索
		SearchCondition sc = new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER, SearchCondition.EQUAL, number );
		qs.appendSearchCondition(sc);
		
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			WTPartMaster master = (WTPartMaster) qr.nextElement();
			if( master != null ){
				part = getWTPartByNumViewAndVersion( master , view , version) ;
			}
		}

		return part ;
	}
	
	/**
	 * 根据零部件主数据(master)和视图获取对应最新版本零部件
	 * @author Harry Cao
	 * @param master
	 * @param view
	 * @return
	 * @throws WTException
	 */
	public static WTPart getWTPartByNumViewAndVersion(WTPartMaster master , String view , String version) throws WTException {
		WTPart part = null;
		//根据视图名称获取视图对象
		View viewObj = ViewHelper.service.getView(view);

		//根据视图构造产品结构配置规范
		WTPartStandardConfigSpec standardConfig = WTPartStandardConfigSpec.newWTPartStandardConfigSpec(viewObj, null);
		try {
			standardConfig.setView(viewObj);
		} catch (WTPropertyVetoException wpve) {
			throw new WTException(wpve);
		}

		//根据master和视图获取对应最新的视图版本零部件
		//QueryResult qr = ConfigHelper.service.filteredIterationsOf(master, standardConfig);
		
		//获取所有版本的零部件
		QueryResult qr=VersionControlHelper.service.allIterationsOf(master);
		//System.out.println(">>>>> 根据编号和视图获取到的零部件对象数量为：" + qr.size()) ;
		
		while ( qr.hasMoreElements() ) {
			part = (WTPart) qr.nextElement();
			
			String partVersion = getVersion( part ) ;
			if(version.equals( partVersion ) && part.getViewName().equals(view)){
				return part ;
			}
		}
		
		
		return null ;
	}
	
	/**
	 * 获取对象的大小版本组成的版本序列值，形如： A.1
	 * 
	 * @param revisionControlled
	 * @return
	 */
	public static String getVersion(RevisionControlled revisionControlled){

		String version = "";
		
		if( revisionControlled != null ){
			//获取大版本
			String majorVersion = revisionControlled.getVersionIdentifier().getValue();
			
			
			// 获取小版本
			//String minorVersion = revisionControlled.getIterationIdentifier().getValue();

			version = majorVersion;
		}
		
		return version;
	}
	
}
